package com.ecp.util;

import java.io.StringWriter;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

import com.ecp.commons.Global;

public class VelocityUtil {
	private static VelocityEngine	velocityEngine	= null;
	private static final String		BASE_DIR		= "Velocity/template/";

	private static void init() {
		if (velocityEngine == null) {
			velocityEngine = new VelocityEngine();
			String FILE_RESOURCE_LOADER_PATH = (String) Global.GLOBALCONFIG.get("REALPATH") + BASE_DIR;
			Properties properties = new Properties();
			properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, FILE_RESOURCE_LOADER_PATH);
			properties.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
			properties.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
			properties.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
			velocityEngine.init(properties);
		}
	}

	public static String merge(VelocityContext context, String templateName) {
		init();
		Template template = velocityEngine.getTemplate(templateName);
		StringWriter writer = new StringWriter();
		template.merge(context, writer);
		return writer.toString();
	}
}
